<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <style>
        canvas {
            margin: 6px auto;
            height: 144px;
            width: 600px;
            border: 1px solid lawngreen;
        }
    </style>
    <title>像素操作</title>
</head>

<body>
    <canvas id="canvas-1"></canvas>
    <button id="refreshBtn">刷新</button>
    <canvas id="canvas-2"></canvas>
    <canvas id="canvas-3"></canvas>
    <canvas id="canvas-4"></canvas>

    <script>
        (function() {
            let canvas = document.getElementById('canvas-1');
            let ctx = canvas.getContext('2d');
            let imgData = ctx.createImageData(canvas.width, canvas.height);
            document.getElementById('refreshBtn').addEventListener("click", function() {
                let base = 20;
                for (let i = 0; i < canvas.width * canvas.height; i = i + base) {
                    let r = Math.floor(Math.random() * 255);
                    let g = Math.floor(Math.random() * 255);
                    let b = Math.floor(Math.random() * 255);
                    for (let j = 0; j < base; j++) {
                        for (let k = 0; k < base; k++) {
                            imgData.data[4 * (i + k + canvas.width * j) + 0] = r;
                            imgData.data[4 * (i + k + canvas.width * j) + 1] = g;
                            imgData.data[4 * (i + k + canvas.width * j) + 2] = b;
                            imgData.data[4 * (i + k + canvas.width * j) + 3] = 255;
                        }
                    }

                    if (i > 0 && i % canvas.width == 0)
                        i = i + (canvas.width * (base - 1));
                }
                ctx.clearRect(0, 0, canvas.width, canvas.height)
                ctx.putImageData(imgData, 0, 0)
            });
            document.getElementById('refreshBtn').click();
        })();
        (function() {
            let canvas = document.getElementById('canvas-4');
            let ctx = canvas.getContext('2d');
            // ctx.fillRect(20, 20, 120, 60);
            // ctx.globalCompositeOperation = "source-in";
            ctx.arc(110, 55, 10, 0, 2 * Math.PI, true);
            ctx.fillStyle = "red";
            ctx.fill();
        })();
        (function() {
            let canvas = document.getElementById('canvas-3');
            let ctx = canvas.getContext('2d');
            ctx.ellipse(120, 72, 100, 32, 0.2 * Math.PI, 0, 1.5 * Math.PI);
            ctx.fill();
        })();
    </script>
</body>

</html>